import requests
import re
import json
import logging


def get_latest_stock_info(stock_id):
    """
    查询某只股票的最新价格等信息。

    :param stock_id: str，例如 '000001'
    :return: dict，包含股票信息；查询失败时返回 None
    """
    try:
        url = f"https://push2.eastmoney.com/api/qt/stock/get?invt=2&fltt=1&cb=jQuery351004935203543461253_1747732615154&fields=f58%2Cf57%2Cf43%2Cf170%2Cf169%2Cf47%2Cf171%2Cf44%2Cf45%2Cf46%2Cf60%2Cf162%2Cf168&secid=0.{stock_id}&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&dect=1"

        headers = {
            "User-Agent": "Mozilla/5.0",
            "Referer": "https://www.eastmoney.com/",
        }

        res = requests.get(url, headers=headers)
        res.raise_for_status()

        res_text = re.search(r'\{.+\}', res.text).group(0)
        res_dict = json.loads(res_text)

        if 'data' not in res_dict:
            logging.warning(f"[get_latest_stock_info] 获取失败，找不到data字段，股票ID: {stock_id}")
            return None

        data = res_dict['data']

        return {
            '股票代码': data.get('f57'),
            '股票名称': data.get('f58'),
            '最新价': data.get('f43'),
            '涨跌幅': data.get('f170'),
            '涨跌额': data.get('f169'),
            '成交量': data.get('f47'),
            '振幅': data.get('f171'),
            '最高': data.get('f44'),
            '最低': data.get('f45'),
            '今开': data.get('f46'),
            '昨收': data.get('f60'),
            '市盈率': data.get('f162'),
            '换手率': data.get('f168'),
        }

    except Exception as e:
        logging.error(f"[get_latest_stock_info] 获取股票信息失败，股票ID: {stock_id}, 错误: {e}")
        return None

def get_latest_fund_info(fund_code):
    """
    查询某只基金的最新价格等信息。

    :param fund_code: str，例如 '161039'
    :return: dict，包含基金信息；查询失败时返回 None
    """
    try:
        # 构造URL，使用东方财富的接口
        #url = f"https://push2.eastmoney.com/api/qt/stock/get?invt=2&fltt=1&cb=jQuery351004935203543461253_1747732615154&fields=f58%2Cf57%2Cf43%2Cf170%2Cf169%2Cf44%2Cf45%2Cf46%2Cf60%2Cf162%2Cf168&secid=1.{fund_code}&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&dect=1"
        url = f"https://push2.eastmoney.com/api/qt/stock/get?invt=2&fltt=1&cb=jQuery35103064516036147804_1749025159764&fields=f58%2Cf734%2Cf107%2Cf57%2Cf43%2Cf59%2Cf169%2Cf170%2Cf152%2Cf46%2Cf60%2Cf44%2Cf45%2Cf47%2Cf48%2Cf19%2Cf17%2Cf531%2Cf15%2Cf13%2Cf11%2Cf20%2Cf18%2Cf16%2Cf14%2Cf12%2Cf39%2Cf37%2Cf35%2Cf33%2Cf31%2Cf40%2Cf38%2Cf36%2Cf34%2Cf32%2Cf211%2Cf212%2Cf213%2Cf214%2Cf215%2Cf210%2Cf209%2Cf208%2Cf207%2Cf206%2Cf161%2Cf49%2Cf171%2Cf50%2Cf86%2Cf168%2Cf108%2Cf167%2Cf71%2Cf292%2Cf51%2Cf52%2Cf191%2Cf192%2Cf452%2Cf177&secid=1.{fund_code}&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&dect=1&_=1749025159765"
        headers = {
            "User-Agent": "Mozilla/5.0",
            "Referer": "https://www.eastmoney.com/",
        }

        res = requests.get(url, headers=headers)
        res.raise_for_status()

        res_text = re.search(r'\{.+\}', res.text).group(0)
        res_dict = json.loads(res_text)

        if 'data' not in res_dict:
            logging.warning(f"[get_latest_fund_info] 获取失败，找不到data字段，基金代码: {fund_code}")
            return None

        data = res_dict['data']


        return {
            '基金代码': data.get('f57'),
            '基金名称': data.get('f58'),
            '最新净值': data.get('f43'),
            '涨跌幅': data.get('f170'),
            '涨跌额': data.get('f169'),
            '今开净值': data.get('f46'),
            '最高净值': data.get('f44'),
            '最低净值': data.get('f45'),
            '昨收净值': data.get('f60'),
            '市盈率': data.get('f162'),
            '换手率': data.get('f168'),
        }

    except Exception as e:
        logging.error(f"[get_latest_fund_info] 获取基金信息失败，基金代码: {fund_code}, 错误: {e}")
        return None



if __name__ == '__main__':
    print(json.dumps(get_latest_stock_info('300149'),ensure_ascii=False, indent=2))